﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace GlTool.GlHttp
{
    /// <summary>
    /// http get请求
    /// </summary>
    public class GlHttpPost : GlHttpBase
    {

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="url">需要访问的url</param>
        public GlHttpPost(String url)
        {
            this.Url = url;
        }

        /// <summary>
        /// 表单数据
        /// </summary>
        private Dictionary<String, object> formMap;

        /// <summary>
        /// 添加保单数据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void setForm(String key, object value)
        {
            if (formMap == null)
            {
                formMap = new Dictionary<string, object>();
            }
            formMap.Add(key, value);
        }

        /// <summary>
        /// 添加保单数据
        /// </summary>
        /// <param name="queryMap"></param>
        public void setForm(Dictionary<String, object> formMap)
        {
            if (formMap == null)
            {
                formMap = new Dictionary<string, object>();
            }

            foreach (var item in formMap)
            {
                this.formMap.Add(item.Key, item.Value);
            }
        }

        /// <summary>
        /// 执行
        /// </summary>
        /// <returns></returns>
        public override GlHttpResponse Execute()
        {
            GlHttpResponse response = new GlHttpResponse();

            //获取请求
            HttpWebRequest request = this.getRequest();

            //设置提交方式为Post
            request.Method = "POST";

            //如果没有设置ContentType则设置默认  否则服务器取法接收到值
            if (request.ContentType == null)
            {
                request.ContentType = "application/x-www-form-urlencoded";
            }


            StringBuilder formSb = new StringBuilder();
            if (formMap != null && formMap.Count > 0)
            {
                //添加form参数
                foreach (var item in formMap)
                {
                    formSb.Append(item.Key).Append('=').Append(item.Value + "&");
                }

                formSb.Length = formSb.Length - 1;
            }

            //解决中文乱码
            var formData = Encoding.UTF8.GetBytes(formSb.ToString());

            //获取上传流
            Stream dataStream = request.GetRequestStream(); ;
            dataStream.Write(formData, 0, formData.Length);
            dataStream.Close();

            //得到请求数据
            response.Response = (HttpWebResponse)request.GetResponse();
            return response;
        }
    }
}
